'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';

interface CheckItem {
  id: number;
  productId: number;
  systemQuantity: number;
  actualQuantity: number;
  discrepancy: number;
  notes: string | null;
  checkedBy: string | null;
  checkedAt: string | null;
  productName: string;
  productSku: string;
}

interface InventoryCheck {
  id: number;
  checkNumber: string;
  checkDate: string;
  status: 'draft' | 'in_progress' | 'completed' | 'cancelled';
  totalItems: number;
  checkedItems: number;
  discrepancies: number;
  notes: string | null;
  createdAt: string;
  items: CheckItem[];
}

export default function InventoryCheckDetailPage() {
  const params = useParams();
  const router = useRouter();
  const [check, setCheck] = useState<InventoryCheck | null>(null);
  const [loading, setLoading] = useState(true);
  const [editingItem, setEditingItem] = useState<CheckItem | null>(null);
  const [actualQuantity, setActualQuantity] = useState('');
  const [notes, setNotes] = useState('');

  useEffect(() => {
    if (params.id) {
      fetchCheckDetail();
    }
  }, [params.id]);

  const fetchCheckDetail = async () => {
    try {
      const response = await fetch(`/api/inventory/check/${params.id}`);
      if (response.ok) {
        const data = await response.json();
        setCheck(data);
      } else {
        console.error('获取盘点详情失败:', await response.json());
      }
    } catch (error) {
      console.error('获取盘点详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleEditItem = (item: CheckItem) => {
    setEditingItem(item);
    setActualQuantity(item.actualQuantity.toString());
    setNotes(item.notes || '');
  };

  const handleSaveItem = async () => {
    if (!editingItem || !actualQuantity) return;

    try {
      const response = await fetch(`/api/inventory/check/${params.id}/items`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          itemId: editingItem.id,
          actualQuantity: parseInt(actualQuantity),
          notes: notes,
          checkedBy: 'user',
        }),
      });

      if (response.ok) {
        setEditingItem(null);
        setActualQuantity('');
        setNotes('');
        fetchCheckDetail(); // 刷新数据
      } else {
        const errorData = await response.json();
        alert('保存失败: ' + (errorData.error || '未知错误'));
      }
    } catch (error) {
      console.error('保存盘点明细失败:', error);
      alert('保存失败，请重试');
    }
  };

  const handleCompleteCheck = async () => {
    if (!confirm('确定要完成盘点吗？完成后将无法修改。')) return;
    
    // 这里实现完成盘点的逻辑
    alert('盘点完成功能待实现');
  };

  const getStatusText = (status: string) => {
    const statusMap = {
      'draft': '草稿',
      'in_progress': '进行中',
      'completed': '已完成',
      'cancelled': '已取消'
    };
    return statusMap[status as keyof typeof statusMap] || status;
  };

  const getStatusColor = (status: string) => {
    const colorMap = {
      'draft': 'bg-gray-100 text-gray-800',
      'in_progress': 'bg-blue-100 text-blue-800',
      'completed': 'bg-green-100 text-green-800',
      'cancelled': 'bg-red-100 text-red-800'
    };
    return colorMap[status as keyof typeof colorMap] || 'bg-gray-100 text-gray-800';
  };

  if (loading) return <div className="p-8">加载中...</div>;
  if (!check) return <div className="p-8">盘点单不存在</div>;

  const uncheckedItems = check.items.filter(item => !item.checkedAt);
  const checkedItems = check.items.filter(item => item.checkedAt);
  const itemsWithDiscrepancy = check.items.filter(item => item.discrepancy !== 0);

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <Link href="/inventory/check" className="text-gray-600 hover:text-gray-900">
            ← 返回盘点列表
          </Link>
          <div>
            <h1 className="text-3xl font-bold">库存盘点</h1>
            <p className="text-gray-600">单号: {check.checkNumber}</p>
          </div>
        </div>
        <div className="flex items-center space-x-3">
          <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusColor(check.status)}`}>
            {getStatusText(check.status)}
          </span>
          {check.status === 'in_progress' && (
            <button
              onClick={handleCompleteCheck}
              className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700"
            >
              完成盘点
            </button>
          )}
        </div>
      </div>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-gray-800">{check.totalItems}</div>
          <div className="text-sm text-gray-600">总商品数</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-blue-600">{check.checkedItems}</div>
          <div className="text-sm text-gray-600">已盘点</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-orange-600">{uncheckedItems.length}</div>
          <div className="text-sm text-gray-600">待盘点</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-red-600">{check.discrepancies}</div>
          <div className="text-sm text-gray-600">差异数</div>
        </div>
      </div>

      {/* 编辑模态框 */}
      {editingItem && (
        <div className="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-96">
            <h3 className="text-lg font-semibold mb-4">
              盘点 - {editingItem.productName}
            </h3>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  系统数量
                </label>
                <div className="text-lg font-semibold">{editingItem.systemQuantity}</div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  实际数量 *
                </label>
                <input
                  type="number"
                  value={actualQuantity}
                  onChange={(e) => setActualQuantity(e.target.value)}
                  min="0"
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  差异
                </label>
                <div className={`text-lg font-semibold ${
                  parseInt(actualQuantity) - editingItem.systemQuantity > 0 
                    ? 'text-green-600' 
                    : parseInt(actualQuantity) - editingItem.systemQuantity < 0 
                    ? 'text-red-600' 
                    : 'text-gray-600'
                }`}>
                  {parseInt(actualQuantity) - editingItem.systemQuantity > 0 ? '+' : ''}
                  {parseInt(actualQuantity) - editingItem.systemQuantity}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  备注
                </label>
                <textarea
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  placeholder="请输入盘点备注"
                />
              </div>

              <div className="flex justify-end space-x-3">
                <button
                  onClick={() => setEditingItem(null)}
                  className="px-4 py-2 text-gray-700 border border-gray-300 rounded-md"
                >
                  取消
                </button>
                <button
                  onClick={handleSaveItem}
                  className="px-4 py-2 bg-blue-600 text-white rounded-md"
                >
                  保存
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 未盘点商品 */}
      {uncheckedItems.length > 0 && (
        <div className="mb-8">
          <h2 className="text-xl font-semibold mb-4 text-orange-600">
            待盘点商品 ({uncheckedItems.length} 项)
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {uncheckedItems.map((item) => (
              <div key={item.id} className="bg-orange-50 border border-orange-200 rounded-lg p-4">
                <h3 className="font-semibold text-orange-800">{item.productName}</h3>
                <p className="text-sm text-orange-600">SKU: {item.productSku}</p>
                <p className="text-sm text-gray-600 mt-2">系统数量: {item.systemQuantity}</p>
                <button
                  onClick={() => handleEditItem(item)}
                  className="mt-3 px-3 py-1 bg-orange-600 text-white text-sm rounded-md hover:bg-orange-700"
                >
                  开始盘点
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 已盘点商品 */}
      {checkedItems.length > 0 && (
        <div>
          <h2 className="text-xl font-semibold mb-4 text-green-600">
            已盘点商品 ({checkedItems.length} 项)
          </h2>
          <div className="bg-white rounded-lg shadow overflow-hidden">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    商品名称
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    系统数量
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    实际数量
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    差异
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    盘点时间
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {checkedItems.map((item) => (
                  <tr key={item.id}>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div>
                        <div className="text-sm font-medium text-gray-900">{item.productName}</div>
                        <div className="text-sm text-gray-500">{item.productSku}</div>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {item.systemQuantity}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {item.actualQuantity}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                        item.discrepancy > 0 ? 'bg-green-100 text-green-800' :
                        item.discrepancy < 0 ? 'bg-red-100 text-red-800' :
                        'bg-gray-100 text-gray-800'
                      }`}>
                        {item.discrepancy > 0 ? '+' : ''}{item.discrepancy}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {item.checkedAt ? new Date(item.checkedAt).toLocaleString('zh-CN') : '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                      <button
                        onClick={() => handleEditItem(item)}
                        className="text-blue-600 hover:text-blue-900"
                      >
                        修改
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* 差异报告 */}
      {itemsWithDiscrepancy.length > 0 && (
        <div className="mt-8">
          <h2 className="text-xl font-semibold mb-4 text-red-600">
            库存差异报告 ({itemsWithDiscrepancy.length} 项)
          </h2>
          <div className="bg-red-50 border border-red-200 rounded-lg p-4">
            {itemsWithDiscrepancy.map((item) => (
              <div key={item.id} className="mb-3 last:mb-0">
                <div className="flex justify-between items-center">
                  <span className="font-medium">{item.productName}</span>
                  <span className={`font-bold ${
                    item.discrepancy > 0 ? 'text-green-600' : 'text-red-600'
                  }`}>
                    {item.discrepancy > 0 ? '+' : ''}{item.discrepancy}
                  </span>
                </div>
                <div className="text-sm text-gray-600">
                  {item.systemQuantity} → {item.actualQuantity}
                  {item.notes && ` (${item.notes})`}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}